<template>
  <div>
    <div class="card px-3 pt-3 mb-3">
      <el-form @submit.native.prevent :inline="true">
        <el-form-item>
          <el-date-picker
            v-model="formData.dateRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            unlink-panels
            @change="handleQuery"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" icon="el-icon-search" @click="getData()">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="row">
      <div class="col-6">
        <div class="card p-3 mb-3">
          <el-echarts
            theme="macarons"
            ref="chartRef"
            :height="360"
            :option="chartOptionArea"
          ></el-echarts>
        </div>
      </div>
      <div class="col-6">
        <div class="card p-3 mb-3">
          <el-echarts
            theme="macarons"
            ref="chartRef"
            :height="360"
            :option="chartOptionBank"
          ></el-echarts>
        </div>
      </div>
      <div class="col-6">
        <div class="card p-3 mb-3">
          <el-echarts
            theme="macarons"
            ref="chartRef"
            :height="360"
            :option="chartOptionIndustry"
          ></el-echarts>
        </div>
      </div>
      <div class="col-6">
        <div class="card p-3 mb-3">
          <el-echarts
            theme="macarons"
            ref="chartRef"
            :height="360"
            :option="chartOptionCredit"
          ></el-echarts>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMonthLastDayDate } from '@/common/plugins/tools/date'
// import { dateFormat } from '@/common/utils/common'

export default {
  components: {},
  props: {},
  data() {
    return {
      loading: false,
      formData: {
        dateRange: [],
      },

      chartOptionArea: {},
      chartOptionBank: {},
      chartOptionIndustry: {},
      chartOptionCredit: {},
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  watch: {},
  created() {
    this.setDateParams()
    this.getData()
  },
  mounted() {},
  methods: {
    setDateParams(date = new Date()) {
      const year = date.getFullYear()
      const month = date.getMonth()
      const start = new Date(year, 0, 1)
      const end = getMonthLastDayDate(year, month)

      this.formData.dateRange = [start, end]
    },
    handleQuery() {
      this.getData()
    },
    getData() {
      this.getAreaData().then(res => {
        const legendData = []
        const seriesData = []
        for (const d of res) {
          legendData.push(d.name)
          seriesData.push({
            name: d.name,
            value: d.funds,
            count: d.count,
          })
        }
        this.chartOptionArea = this.setOption({
          title: '区域代偿分析',
          seriesName: '区域',
          legendData,
          seriesData,
        })
      })

      this.getBankData().then(res => {
        const legendData = []
        const seriesData = []
        for (const d of res) {
          legendData.push(d.name)
          seriesData.push({
            name: d.name,
            value: d.funds,
            count: d.count,
          })
        }
        this.chartOptionBank = this.setOption({
          title: '银行代偿分析',
          seriesName: '银行',
          legendData,
          seriesData,
        })
      })

      this.getIndustryData().then(res => {
        const legendData = []
        const seriesData = []
        for (const d of res) {
          legendData.push(d.name)
          seriesData.push({
            name: d.name,
            value: d.funds,
            count: d.count,
          })
        }
        this.chartOptionIndustry = this.setOption({
          title: '产业代偿分析',
          seriesName: '产业',
          legendData,
          seriesData,
        })
      })

      this.getCreditData().then(res => {
        const legendData = []
        const seriesData = []
        for (const d of res) {
          legendData.push(d.name)
          seriesData.push({
            name: d.name,
            value: d.funds,
            count: d.count,
          })
        }
        this.chartOptionCredit = this.setOption({
          title: '担保机构代偿分析',
          seriesName: '担保机构',
          legendData,
          seriesData,
        })
      })
    },
    async getAreaData() {
      const params = {
        groupFields: ['county_code', 'county_code_name'],
        groupFunc: `count(1),round(sum(compens_funds)|2)`,
        fields: ['county_code', 'county_code_name'],
        'orWhere.service_id.eq': this.clientId,
        'orWhere.recommend_service.eq': this.clientId,
      }
      const [startDate, endDate] = this.formData.dateRange
      const hasDate = startDate && endDate
      if (hasDate) {
        // const start = dateFormat(startDate, 'yyyy-MM-dd')
        // const end = `${dateFormat(endDate, 'yyyy-MM-dd')} 23:59:59`
        // params['load_date.gte'] = start
        // params['load_date.lte'] = end
      }
      const res = await this.$api.getData(this.$serviceName, 'comps_analysis_for_address', params)
      return (res.data || []).map(it => ({
        name: it.county_code_name,
        count: it.p,
        funds: it.p1,
      }))
    },
    async getBankData() {
      const params = {
        groupFields: ['bank_type', 'bank_type_name'],
        groupFunc: `count(1),round(sum(compens_funds)|2)`,
        fields: ['bank_type', 'bank_type_name'],
        'orWhere.service_id.eq': this.clientId,
        'orWhere.recommend_service.eq': this.clientId,
      }
      const [startDate, endDate] = this.formData.dateRange
      const hasDate = startDate && endDate
      if (hasDate) {
        // const start = dateFormat(startDate, 'yyyy-MM-dd')
        // const end = `${dateFormat(endDate, 'yyyy-MM-dd')} 23:59:59`
        // params['load_date.gte'] = start
        // params['load_date.lte'] = end
      }
      const res = await this.$api.getData(this.$serviceName, 'comps_analysis_for_bank', params)
      return (res.data || []).map(it => ({
        name: it.bank_type_name,
        count: it.p,
        funds: it.p1,
      }))
    },
    async getIndustryData() {
      const params = {
        groupFields: ['main_business'],
        groupFunc: `count(1),round(sum(compens_funds)|2)`,
        fields: ['main_business'],
        'orWhere.service_id.eq': this.clientId,
        'orWhere.recommend_service.eq': this.clientId,
      }
      const [startDate, endDate] = this.formData.dateRange
      const hasDate = startDate && endDate
      if (hasDate) {
        // const start = dateFormat(startDate, 'yyyy-MM-dd')
        // const end = `${dateFormat(endDate, 'yyyy-MM-dd')} 23:59:59`
        // params['load_date.gte'] = start
        // params['load_date.lte'] = end
      }
      const res = await this.$api.getData(this.$serviceName, 'comps_analysis_for_ind', params)
      return (res.data || []).map(it => ({
        name: it.main_business,
        count: it.p,
        funds: it.p1,
      }))
    },
    async getCreditData() {
      const params = {
        groupFields: ['gua_type', 'gua_type_name'],
        groupFunc: `count(1),round(sum(compens_funds)|2)`,
        fields: ['gua_type', 'gua_type_name'],
        'orWhere.service_id.eq': this.clientId,
        'orWhere.recommend_service.eq': this.clientId,
      }
      const [startDate, endDate] = this.formData.dateRange
      const hasDate = startDate && endDate
      if (hasDate) {
        // const start = dateFormat(startDate, 'yyyy-MM-dd')
        // const end = `${dateFormat(endDate, 'yyyy-MM-dd')} 23:59:59`
        // params['load_date.gte'] = start
        // params['load_date.lte'] = end
      }
      const res = await this.$api.getData(this.$serviceName, 'comps_analysis_for_gua', params)
      return (res.data || []).map(it => ({
        name: it.gua_type_name,
        count: it.p,
        funds: it.p1,
      }))
    },
    setOption(data) {
      return {
        backgroundColor: '#f8f9fa',
        title: {
          text: data.title,
          subtext: '',
          left: 'center',
          top: 10,
        },
        grid: {
          top: 80,
          left: 50,
          right: 80,
          bottom: 80,
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return `${params.name}<br>
            ${params.marker}
            共${params.data.count}个项目，
            金额${params.value}万元，
            占比${params.percent}%`
          },
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
          top: 10,
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          left: 'center',
          bottom: 20,
          data: data.legendData,
        },
        series: [
          {
            name: data.seriesName,
            type: 'pie',
            radius: '50%',
            center: ['50%', '50%'],
            data: data.seriesData,
            label: {
              formatter: '{b} ({d}%)',
            },
          },
        ],
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
